import { createRouter, createWebHashHistory } from 'vue-router';
import LoginPage from '../components/LoginPage.vue';
import HomePage from '../components/HomePage.vue';
import { useAccountStore } from './AccountStore';
import Operational from '../components/Operational.vue';
import OperationalAdd from '../components/OperationalAdd.vue';
import Category from '../components/Category.vue';
import GoodsEdit from '../components/GoodsEdit.vue';
import GoodsManager from '../components/GoodsManager.vue';

// 定义页面名称枚举
export enum PageName {
    login = 'login',
    home = 'home'
}
// 定义路由
const shopRouter = createRouter({
    history: createWebHashHistory(),
    routes: [
        {
            path: '/login',
            name: PageName.login,
            component: LoginPage,
        }, {
            path: '/home',
            name: PageName.home,
            component: HomePage,
            children: [ // 子路由列表
                {
                    path: 'operational', // 子路由路径为'operational'
                    component: Operational, //对应的路由组件
                    name: 'Operational',
                }, {
                    path: 'operationalAdd', // 子路由路径
                    component: OperationalAdd,
                    name: 'OperationalAdd',
                }, {
                    path: 'category',     
                    component: Category,
                    name: 'category'
                }, {
                    path: 'goodsEdit/:mode?/:id?',
                    component: GoodsEdit,
                    name: 'goodsEdit',
                }, {
                    path: 'goodsManager',
                    component: GoodsManager,
                    name: 'goodsManager',
                }
            ],
            redirect: '/home/operational'
        }, 
    ]
});
// 定义前置守卫
shopRouter.beforeEach((to) => {
    const accountStore = useAccountStore();
    
    if (to.name !== PageName.login && (!accountStore.isLogin || accountStore.userInfo?.role !== 'admin')) {
        return {
            name: PageName.login
        }
    }
});
// 导出路由
export default shopRouter;
